package com.wtp.wallpaper.controller.admin;

import com.wtp.wallpaper.common.constant.PictureOssPathConstant;
import com.wtp.wallpaper.common.constant.RedisConstant;
import com.wtp.wallpaper.mapper.PictureMapper;
import com.wtp.wallpaper.pojo.dto.PictureDTO;
import com.wtp.wallpaper.pojo.entity.User;
import com.wtp.wallpaper.pojo.result.Result;
import com.wtp.wallpaper.bloomfilter.BloomFilterService;
import com.wtp.wallpaper.service.PictureService;
import com.wtp.wallpaper.service.UserService;
import com.wtp.wallpaper.utils.PictureReduceUtil;
import com.wtp.wallpaper.utils.UnzipUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private BloomFilterService bloomFilterService;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/login")
    public Result validate(@RequestBody User user){
        log.info("管理员{}登录",user);
        return Result.success(userService.login(user));
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file)  {

        String fileMd5 = null;
        //判断图片是否重复
        try {
            Object[] repeat = pictureService.isRepeat(file.getInputStream());
            fileMd5 = (String) repeat[0];
            if(repeat[1].equals(true)){
                return Result.error("图片已存在!");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        String filename = file.getOriginalFilename();
        assert filename != null;
        filename = UUID.randomUUID() + filename.substring(filename.lastIndexOf('.'));

        log.info("上传文件：{}",filename);
        // 文件保存路径 保存在磁盘未处理地方
        String filePath = PictureOssPathConstant.DEFAULT_TEMP;
        // 记录到 Redis（键永不过期，由定时任务管理）
        redisTemplate.opsForValue().set(RedisConstant.UPLOAD_IMAGE + filename,System.currentTimeMillis());



        // 将文件保存到指定路径
        try {
            PictureReduceUtil.checkPath(filePath);
            file.transferTo(new File(filePath + filename));
        } catch (IOException e) {
            log.error("保存本地出错");
            throw new RuntimeException(e);
        }
        return Result.success(PictureDTO.builder()
                .fileMd5(fileMd5)
                .fileName(filename)
                .build());
    }

    @PostMapping("/uploadBatch")
    public Result uploadBatch(@RequestParam("files") MultipartFile file) throws IOException {

        String filename = null;
        try {
            filename = file.getOriginalFilename();
            log.info("上传文件：{}",filename);
            UnzipUtil.extractArchive(file, PictureOssPathConstant.DEFAULT_TEMP);
            filename = filename.substring(0, filename.lastIndexOf('.'));
            redisTemplate.opsForValue().set(RedisConstant.UPLOAD_BATCH + PictureOssPathConstant.DEFAULT_TEMP + filename,System.currentTimeMillis());
            pictureService.addPictureBatch(Paths.get(PictureOssPathConstant.DEFAULT_TEMP,filename));

            return Result.success("上传成功");
        } catch (Exception e) {
            return Result.error("上传失败");
        }
    }

}
